package com.zjj.algorithm.learning.atguigu.search;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 二分查找：前提数组必须是有序的
 *
 * @author zjj_admin
 * @date 2022/11/20 13:50
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 1, 1, 1, 8, 10, 89, 1000, 1000, 1000, 1236};
//        int res = binarySearch(arr, 0, arr.length - 1, 1000);
        List<Integer> res = binarySearchAll(arr, 0, arr.length - 1, 5);
        System.out.println("res = " + res);
    }


    /**
     * @param arr
     * @param left
     * @param right
     * @param value
     * @return
     */
    public static int binarySearch(int[] arr, int left, int right, int value) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if (midVal < value) {
            //当中间值小于需要寻找的值时，就需要向右递归
            return binarySearch(arr, mid + 1, right, value);
        } else if (midVal > value) {
            //当中间值大于了需要寻找的值时，就向左递归
            return binarySearch(arr, left, mid - 1, value);
        } else {
            return mid;
        }
    }


    /**
     * 当数组中有很多歌被查找元素时，需要返回所有的下标
     *
     * @param arr
     * @param left
     * @param right
     * @param value
     * @return
     */
    public static List<Integer> binarySearchAll(int[] arr, int left, int right, int value) {
        if (left > right) {
            return new ArrayList<>();
        }
        int mid = (left + right) / 2;
        int midVal = arr[mid];
        if (midVal < value) {
            //当中间值小于需要寻找的值时，就需要向右递归
            return binarySearchAll(arr, mid + 1, right, value);
        } else if (midVal > value) {
            //当中间值大于了需要寻找的值时，就向左递归
            return binarySearchAll(arr, left, mid - 1, value);
        } else {
            List<Integer> resList = new ArrayList<>();
            int temp = mid - 1;
            while (true) {
                if (temp < 0 || arr[temp] != value) {
                    break;
                }
                resList.add(temp);
                temp--;
            }
            resList.add(mid);
            temp = mid + 1;
            while (true) {
                if (temp > arr.length - 1 || arr[temp] != value) {
                    break;
                }
                resList.add(temp);
                temp++;
            }

            return resList;
        }
    }
}
